from nicegui import ui


class TableHighlighter:
    css_variables = "--selected-bg-color"

    def __init__(self, color: str = "#f7f7f7", auto_inject_static=True) -> None:
        self.color = color
        self.previous_selected_index = None
        if auto_inject_static:
            self.inject_static_for_table_selected_effect()

    def inject_static_for_table_selected_effect(self):
        ui.add_body_html(
            r"""
        <script>
        function setBackgroundToCssVariable(selector, cssVariableName) {
        // 获取所有匹配的元素
            const element = document.querySelector(selector);
            element.style.backgroundColor = `var(${cssVariableName})`;
            element.setAttribute('data-mark-as-selected','');
        }

        function removeBackgroundColor(selector) {
        // 获取所有匹配给定选择器的元素
            const elements = document.querySelectorAll(selector);


            elements.forEach(element => {
                element.style.removeProperty('background-color');
            });
        }

        </script>
        """
        )
        ui.add_css(
            rf"""
        .q-table tbody tr:hover {{
            background-color: var({self.css_variables});
        }}
        """
        )

    def _run_setBackgroundToCssVariable(self, table: ui.table, nth: int):
        table_id = table.id
        ui.run_javascript(
            f"setBackgroundToCssVariable(`#c{table_id} tbody tr:nth-child({nth})`, `{self.css_variables}`) "
        )

    def apply(self, table: ui.table):
        def row_click(e):
            index = e.args[-1]
            self.previous_selected_index = index
            self._run_setBackgroundToCssVariable(table, index + 1)

        def mouseenter():
            ui.run_javascript(
                f"removeBackgroundColor(`#c{table.id} tbody tr[data-mark-as-selected]`)"
            )
            self.previous_selected_index = None

        table.on("rowClick", row_click).on(
            "mouseenter",
            mouseenter,
        ).style(f"--selected-bg-color:{self.color}")

        if self.previous_selected_index is not None:
            self._run_setBackgroundToCssVariable(
                table, self.previous_selected_index + 1
            )
            self.previous_selected_index = None

        return table


columns = [
    {
        "name": "name",
        "label": "Name",
        "field": "name",
        "required": True,
        "align": "left",
    },
    {"name": "age", "label": "Age", "field": "age", "sortable": True},
]
rows = [
    {"name": "Alice", "age": 18},
    {"name": "Bob", "age": 21},
    {"name": "Carol"},
]


def row_click(e):
    dialog.open()


table_highlighter = TableHighlighter("#bbf7d0")

with ui.dialog().props("persistent") as dialog, ui.column():

    def submit():
        dialog.close()

    dialog_input = ui.input(label="Name")
    ui.button("确定", on_click=submit)


@ui.refreshable
def create_table():
    pass

    table = ui.table(columns=columns, rows=rows, row_key="name", pagination=2).on(
        "rowClick", row_click
    )
    table_highlighter.apply(table)


create_table()

ui.button("刷新", on_click=create_table.refresh)


ui.run()
